import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let _openSettingButton = null;
  let showOpenSettingButton = function (text, callback) {
    if (wx.createOpenSettingButton === undefined) {
      return false;
    }
    if (!_openSettingButton) {
      let sysInfo = wx.getSystemInfoSync();
      let width = 515;
      let left = (sysInfo.windowWidth - 515) / 2;
      let height = 65;
      let top = sysInfo.windowHeight - sysInfo.windowHeight * 0.2 - height / 2;
      _openSettingButton = wx.createOpenSettingButton({
        type: 'text',
        text: text,
        style: {
          left: left,
          top: top,
          width: width,
          height: height,
          lineHeight: height,
          color: '#ffffff',
          textAlign: 'center',
          fontSize: 26,
          backgroundColor: '#000000dd',
          // borderRadius: height
        }
      });
      _openSettingButton.onTap(() => {
        _openSettingButton.destroy();
        _openSettingButton = null;
        callback(Global.LoginState);
      });
    }
    return true;
  };
  
  let hideOpenSettingButton = function () {
    if (_openSettingButton) {
      _openSettingButton.destroy();
      _openSettingButton = null;
    }
  };
  let openSetting = function (callback) {
    wx.openSetting({
      success: (res) => {
        console.log("wx.openSetting成功:", res);
        let authSetting = res.authSetting;
        if (authSetting['scope.userInfo'] === true) {
          // 用户已授权，可以直接调用相关 API
          Global.LoginState.isAuthorize = true;
          _getUserInfo(callback);
        } else {
          Global.LoginState.isAuthorize = false;
          callback(Global.LoginState);
        }
      },
      fail: (res) => {
        console.log("wx.openSetting失败:", res);
        Global.LoginState.isAuthorize = false;
        callback(Global.LoginState);
      }
    });
  };
  
  let openSettingWithScope = function (scope, callback) {
    wx.openSetting({
      success: (res) => {
        console.log("wx.openSetting成功:", res);
        let authSetting = res.authSetting;
        if (authSetting['scope'] === true) {
          // 用户已授权，可以直接调用相关 API
          if (callback) {
            callback(true);
          }
          
        } else {
          if (callback) {
            callback(false);
          }
          
        }
      },
      fail: (res) => {
        console.log("wx.openSetting失败:", res);
        if (callback) {
          callback(false);
        }
      }
    });
  };
  
  let gameClubButton;
  let showGameClubButton = function () {
    if (!wx.createGameClubButton)
      return;
    let sysInfo = wx.getSystemInfoSync();
    if (!gameClubButton) {
      //创建游戏圈按钮
      gameClubButton = wx.createGameClubButton({
        icon: 'white',
        style: {
          left: 20,
          top: sysInfo.windowHeight - 130,
          width: 30,
          height: 30
        }
      });
    } else {
      gameClubButton.show();
    }
  };
  
  let hideGameClubButton = function () {
    if (gameClubButton) {
      gameClubButton.hide();
    }
  };
  let getPlatform = function () {
    let sysInfo = wx.getSystemInfoSync();
    return sysInfo.platform;
  };
  
  let checkGameUpdate = function () {
    if (typeof wx.getUpdateManager === 'function') {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log(res.hasUpdate);
      });
      
      updateManager.onUpdateReady(function () {
        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
        updateManager.applyUpdate();
      });
      
      updateManager.onUpdateFailed(function () {
        // 新的版本下载失败
      });
    }
  };
  
  
  /**
   * 当前是否允许保存到相册
   */
  let canSaveToAlbum = function (callback) {
    wx.getSetting({
      success: (res) => {
        console.log("wx.getSetting成功:", res);
        let authSetting = res.authSetting;
        if (authSetting['scope.writePhotosAlbum'] === true) {
          // 用户已授权，可以直接调用相关 API
          if (callback) {
            callback(true);
          }
        } else if (authSetting['scope.writePhotosAlbum'] === false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          if (callback) {
            callback(false);
          }
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: (res) => {
              console.log("wx.authorize成功:", res);
              if (callback) {
                callback(true);
              }
            },
            
            fail: function (res) {
              // iOS 和 Android 对于拒绝授权的回调 errMsg 没有统一，需要做一下兼容处理
              if (res.errMsg.indexOf('auth deny') > -1 || res.errMsg.indexOf('auth denied') > -1) {
                // 处理用户拒绝授权的情况
                if (callback) {
                  callback(false);
                }
              }
            }
          });
        }
      },
      fail: (res) => {
        console.log("wx.getSetting失败:", res);
        if (callback) {
          callback(false);
        }
      }
    });
  };
  /**
   * 保存屏幕截图到系统相册
   * @param callback
   */
  let saveToAlbum = function (callback) {
    let canvas = cc.game.canvas;
    let sysInfo = wx.getSystemInfoSync();
    
    // let width = sysInfo.screenWidth;
    // let height = sysInfo.screenHeight;
    
    let tempFilePath = canvas.toTempFilePathSync({
      // width: width,
      // height: height,
    });
    
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: (res) => {
        if (callback) {
          callback(null, res);
        }
      },
      
      fail: (res) => {
        if (callback) {
          callback(res);
        }
      }
    });
  };
  
  
  let openCustomerService = function (callback) {
    let shareInfo = Global.ShareWatchAdSwitch.defaultShareInfo;
    wx.openCustomerServiceConversation({
      showMessageCard: true,
      sendMessageTitle: shareInfo.title,
      sendMessageImg: shareInfo.imageUrl,
      sendMessagePath: '',
      success: (res) => {
        console.log("openCustomerService.success", res);
        callback && callback(null, res);
      },
      fail: (res) => {
        console.log("openCustomerService.fail", res);
        callback && callback(res);
        
      },
      complete: (res) => {
        console.log("openCustomerService.complete", res);
      }
    });
  };
  
  
  let showFollowMPQRCode = function (callback) {
    let urls = [
      'https://cdn.birdfly.sy3.com/happy-bugs/followMp.jpg'
    ];
    wx.previewImage({
      current: urls[0],
      urls: urls,
      success: function (res) {
        console.log('预览的图片 成功', res);
      },
      fail: function (res) {
        console.log('预览的图片 失败');
      },
      complete: function (res) {
        callback && callback();
      }
    });
  };
  
  
  let installShortcut = function (callback) {
    callback && callback(false);
  };
  
  let hasShortcutInstalled = function (callback) {
    callback && callback(false);
  };
  
  /**
   * 设置游戏加载进度页面
   * @param progress 0-100 的整数
   */
  let setLoadingProgress = function (progress) {
  };
  
  /**
   * 隐藏游戏加载进度页面
   * @param callback
   */
  let loadingComplete = function (callback) {
    callback && callback();
  };
  
  module.exports = {
    showOpenSettingButton,
    hideOpenSettingButton,
    openSetting,
    openSettingWithScope,
    showGameClubButton,
    hideGameClubButton,
    getPlatform,
    checkGameUpdate,
    canSaveToAlbum,
    saveToAlbum,
    openCustomerService,
    showFollowMPQRCode,
    installShortcut,
    hasShortcutInstalled,
    setLoadingProgress,
    loadingComplete,
  }
}